package com.eorchis.module.department.ui.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eorchis.constants.DeptConstants;
import com.eorchis.core.servicetemplate.treetemplate.jsonbean.JsonTreeBean;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.department.domain.DepartmentTreeCondition;
import com.eorchis.module.department.service.IDepartmentTreeService;
import com.eorchis.module.department.ui.commond.DepartmentTreeCommond;
import com.eorchis.module.security.cas.domain.Role;
import com.eorchis.utils.utils.PropertyUtil;

@Controller
@RequestMapping({ "/module/department" })
public class DepartmentTreeController {
	public static final String modulePath = "/module/department";

	@Autowired
	@Qualifier("com.eorchis.module.department.service.impl.DepartmentTreeServiceImpl")
	private IDepartmentTreeService departmentTreeService;

	@RequestMapping({ "/findDepartmentTree" })
	@ResponseBody
	public List<JsonTreeBean> findDepartmentTree(HttpServletRequest request, DepartmentTreeCommond commond) throws Exception {
		List<JsonTreeBean> result = new ArrayList<JsonTreeBean>();
		DepartmentTreeCondition condition = new DepartmentTreeCondition();
		BeanUtils.copyProperties(condition, commond);
		HttpSession session = request.getSession();
		Department casDept = (Department) session.getAttribute(SessionConstant.CURRENT_SCOPE);
		String node="";
//		condition.setProjectId(casDept.getDeptID());
		if (PropertyUtil.objectNotEmpty(condition.getNode())){
			condition.setNode(condition.getNode());
			node=condition.getNode();
		}
		else
			condition.setNode(casDept.getDeptID());
		condition.setFindLeapNode(true);
		result = this.departmentTreeService.doProcess(condition);
		if(node.equals(DeptConstants.DEPT_ROOT_ID)){
			List<JsonTreeBean> result2 = new ArrayList<JsonTreeBean>();
			JsonTreeBean rootBean = new JsonTreeBean();
			commond.setNode(DeptConstants.DEPT_ROOT_ID);
			BeanUtils.copyProperties(commond, condition);
			condition.setFindLeapNode(true);
			rootBean.setText("北京市");
			rootBean.setLeaf(false);
//			rootBean.setChecked(false);
			rootBean.setId(DeptConstants.DEPT_ROOT_ID);
			rootBean.setChildren(result);
			rootBean.setState("close");
			rootBean.setExpandable(true);
			result2.add(rootBean);
			return result2;
		}
		return result;
	}
	
}